package bank;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import bank.BankAccount;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author tank
 */
public class ReaderWriter {
    private String fileName = "Accounts.txt";
     public void writeToFile(BankAccount[] Accounts) {
          FileOutputStream out = null;
        try {

            System.out.println("Saving to file...");
            out = new FileOutputStream(new File(fileName));
            PrintWriter pw = new PrintWriter(out);
            //For each grade
            for (int i = 0; i < Accounts.length; i++) {
                BankAccount B = Accounts[i];
                //Save each grade in the format we decided name : grade on each line
                if(B!=null){
                    String s = B.getAccountName();
                    pw.println(B.getAccountNumber ()+ ":" +B.getAccountName() + ":" + B.getAmount());
                }
            }
            pw.flush();
        } catch (FileNotFoundException ex) {
            System.out.println("Error creating stream to file");
            ex.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                System.out.println("Ignore");
            }
        }

     }
       public BankAccount [] readFromFile()
       {
            FileReader reader = null;
        BankAccount [] result = new BankAccount[10];
        int numberOfResults = 0;
        try {
            reader = new FileReader(new File(fileName));
            BufferedReader br = new BufferedReader(reader);
            String row = br.readLine();
            while(row != null){
                //Process the data in that row

                String [] splits = row.split(":");
                if(splits.length == 3){

                    BankAccount B = new BankAccount(splits[1], Integer.parseInt(splits[0].trim()), Double.parseDouble(splits[2].trim()));
                    result[numberOfResults] = B;
                    numberOfResults++;
                } else {
                    System.out.println("Error in file format");
                }
                //Read a new line
                row = br.readLine();
            }
        } catch (Exception ex) {
            System.out.println("Error reading from file");
            ex.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException ex) {
                System.out.println("Ignore");
            }

        }

            return result;
       }
}





